package order.intercepter;


import cn.hutool.json.JSONUtil;
import com.feign.constant.AuthServerConstant;
import com.feign.vo.LoginResVo;
import order.hodler.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class OrderInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        if (!ObjectUtils.isEmpty(token)) {
            String user = redisTemplate.opsForValue().get(AuthServerConstant.TOKEN + token);
            LoginResVo loginResVo = JSONUtil.toBean(user, LoginResVo.class);
            // 存入threadLocal
            UserHolder.saveUser(loginResVo);
        }
        return true;
    }
}
